package com.share.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Map;
import java.util.UUID;

/**
 * @author sunxuejian
 * @date 2020/10/7
 */
public final class JwtTokenUtil {

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString().replace("-", ""));
    }

    /**
     * 生成token
     * @param payload
     * @return
     */
    public static String genToken(Map<String, Object> payload) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Key key = genKey();
            //token 字符串
            return Jwts.builder().setPayload(objectMapper.writeValueAsString(payload))
                    .signWith(SignatureAlgorithm.HS256, key).compact();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 生成秘钥
     * @return
     */
    private static Key genKey() {
        byte[] bin = DatatypeConverter.parseBase64Binary("sunxj");
        //加密方式
        SignatureAlgorithm saa = SignatureAlgorithm.HS256;
        Key key = new SecretKeySpec(bin, saa.getJcaName());
        return key;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims phaseToken(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(genKey()).parseClaimsJws(token);
        return claimsJws.getBody();
    }
}
